import React, { useEffect, useState } from "react";
import { Editor } from "react-draft-wysiwyg";
import { EditorState, convertToRaw, ContentState } from "draft-js";
import draftToHtml from "draftjs-to-html";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import "./NewsEditor.scss";
import htmlToDraft from "html-to-draftjs";

function NewsEditor(props) {
  const [editorState, setEditorState] = useState(EditorState.createEmpty());
  useEffect(() => {
    if (props.content !== undefined) {
      const contentBlock = htmlToDraft(props.content);
      if (contentBlock) {
        const contentState = ContentState.createFromBlockArray(
          contentBlock.contentBlocks
        );
        const editorState = EditorState.createWithContent(contentState);
        setEditorState(editorState);
      }
    }
  }, [props.content]);
  return (
    <Editor
      editorState={editorState}
      toolbarClassName="toolbarClassName"
      wrapperClassName="wrapperClassName"
      editorClassName="editorClassName"
      onEditorStateChange={editor => {
        setEditorState(editor);
      }}
      onBlur={() => {
        props.getEditContent(
          draftToHtml(convertToRaw(editorState.getCurrentContent()))
        );
      }}
    />
  );
}
export default NewsEditor;
